package org.trc.io;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 建立数据库连接：
 * 
 * 1）装载jdbc驱动程序     Class.forName(); 
 * 2）建立数据库连接     getConnection( jdbc:drivertype:driversubtype://parameters, user, password)
 * 3）创建statement
 * 4）执行查询
 * 5）访问result
 * 
 * @author Lin Xu
 *
 */
public abstract class DBConn {
	
	//获取postgresql数据库连接
	protected static Connection getPgConn(String db, String dbUserName,
			String dbPassword) throws SQLException, ClassNotFoundException {
		Connection conn = null;
		//String dbDriver = "org.postgresql.Driver";
		//String dbDriver = "org.postgis.DriverWrapper";
		String dbDriver = "org.postgis.jts.JtsWrapper"; //加入JTS空间数据类型
		try {
			Class.forName(dbDriver);
			//"jdbc:postgresql://"
			//"jdbc:postgresql_postGIS://"
			conn = DriverManager.getConnection("jdbc:postgres_jts://" + db, dbUserName, dbPassword);
		} catch (Exception e) {
			System.err.println("Postgresql Connection Error: ");
			e.printStackTrace();
		}

		return conn;
	}

	//获取mysql的数据库连接 
	protected static Connection getMySConn(String db, String dbUserName,
			String dbPassword) {
		Connection conn = null;
		String dbDriver = "com.mysql.jdbc.Driver";
		try {
			Class.forName(dbDriver); 
			conn = DriverManager.getConnection("jdbc:mysql://"+db, dbUserName, dbPassword);

		} catch (Exception e) {
			System.err.println("Postgresql Connection Error: ");
			e.printStackTrace();
		}

		return conn;
	}

	//获取查询结果集大小
	protected static int getResultSetSize(ResultSet resultSet) {
		int size = -1;
		try {
			resultSet.last();
			size = resultSet.getRow();
			resultSet.beforeFirst();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return size;
	}

}